package mall.service.impl;

import org.apache.commons.codec.digest.DigestUtils;

import mall.bean.User;
import mall.dao.BaseDao;
import mall.dao.UserDao;
import mall.dao.impl.UserDaoImpl;
import mall.exception.UserNameAlreadyExistsException;
import mall.service.UserService;

public class UserServiceImpl extends BaseServiceImpl<User, Long> implements UserService {
	
	private UserDao userDao = new UserDaoImpl();
	
	@Override
	public BaseDao<User, Long> getDao() {
		return this.userDao;
	}

	@Override
	public User login(String userName, String password)  {
		// 密码加密
		String md5password = DigestUtils.md5Hex(password);
		// 调用userDao的方法进行查询
		User user = this.userDao.findByName(userName);
		// 逻辑判断: 登录成功否
		if (user != null && md5password.equalsIgnoreCase(user.getPassword())) {
			user.setPassword("");
			return user;
		}
		return null;
	}
	
	@Override
	public boolean register(User user)  {
		// 去掉用户名中不小心输出的首尾空格
		String userName = user.getUserName().trim();
		user.setUserName(userName);
		// 1先检查userName是不是和别人重复了, 如果重复了, 抛出异常
		User findByName = this.userDao.findByName(userName);
		if (findByName != null) {
			throw new UserNameAlreadyExistsException("注册用户名[" + user.getUserName().trim() + "]和其他用户重复!");
		}
		// 2对密码进行md5加密
		String md5Pwd = DigestUtils.md5Hex(user.getPassword());
		user.setPassword(md5Pwd);
		// 3保存注册信息到user表
		this.userDao.save(user);
		return true;
	}

}
